﻿using System;
using SmartCard.Framework;
using System.Collections.Generic;

namespace SmartCard.GSM_11_11
{
	public class SelectFileOperation : CardOperation<byte[]>
	{
		#region properties

		public LinkedList<KeyValuePair<ApduCommand, ApduResponse>> History
		{ get; private set; }

		public byte[] FileId
		{ get; private set; }

		#endregion

		#region construction

		public SelectFileOperation(ICard card, byte[] fileId)
			: base(card)
		{
			if (fileId == null)
			{ throw new ArgumentNullException("fileId"); }

			FileId = fileId;
			History = new LinkedList<KeyValuePair<ApduCommand, ApduResponse>>();
		}

		#endregion

		public override byte[] Execute()
		{
			var response = SelectFile();

			// process the response
			if (response.Sw1 != 0x9f &&
				response.Sw1 != 0x90)
			{ throw new SmartCardException("Error from execution"); }

			ApduResponse fileContents = null;
			if (response.Sw1 == 0x9f)
			{ fileContents = GetFileContents(response.Sw2); }

			return fileContents.Data;
		}

		private ApduResponse SelectFile()
		{
			var request = new ApduCommand(0xA0,
				0xA4, 0x00, 0x00, FileId, 0xFF);

			var response = Card.Send(request);
			return response;
		}

		private ApduResponse GetFileContents(byte amountOfData)
		{
			var request = new ApduCommand(0xA0,
				0xC0, 0x00, 0x00, amountOfData, amountOfData);

			var response = Card.Send(request);
			return response;
		}
	}
}
